package br.com.ximp.addessi.server.dao.low;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Query;
import com.google.gwt.core.client.GWT;

import br.com.ximp.addessi.server.dao.ContaDAO;
import br.com.ximp.addessi.server.dao.UsuarioDAO;
import br.com.ximp.addessi.server.service.Objectory;
import br.com.ximp.addessi.shared.entity.Conta;
import br.com.ximp.addessi.shared.entity.TipoConta;
import br.com.ximp.addessi.shared.entity.Usuario;

public class LowContaDAO extends LowDAO implements ContaDAO {
	private static final Logger log = Logger.getLogger(LowContaDAO.class.getName());
	private static final String CONTA = "Conta";

	@Override
	public List<Conta> findTodas(String email) {
		List<Conta> contas = new ArrayList<Conta>();
		LowUsuarioDAO usuarioDAO = (LowUsuarioDAO) Objectory.getUsuarioDAO(); //REMOVE STINK
		Usuario usuario = usuarioDAO.getByEmail(email);
		Entity eUsuario = usuarioDAO.toEntity(usuario);
		Key parent = eUsuario.getKey();
		Query q = new Query(CONTA,parent);
		DatastoreService ds = getDatastore();
		Iterable<Entity> it = ds.prepare(q).asIterable();
		if(it.iterator().hasNext()){
			for(Entity e:it){
				contas.add(fromEntity(e));
			}
		}else{
			Conta conta = new Conta();
			conta.setTipoConta(TipoConta.corrente);
			conta.setNome("Minha conta");
			contas.add(fromEntity(toEntity(conta,parent)));
		}
		return contas;
	}

	private Entity toEntity(Conta conta, Key parent) {
		DatastoreService ds = getDatastore();
		Entity e = null;
		if(conta.getId() == null){
			e = new Entity(CONTA,parent);
		}else{
			try {
				e = ds.get(KeyFactory.createKey(CONTA, conta.getId()));
			} catch (EntityNotFoundException e1) {
				log.log(Level.SEVERE, e1.getMessage(), e1);				
			}
		}
		e.setProperty("nome",conta.getNome());
		e.setProperty("tipoConta",conta.getTipoConta().name());
		ds.put(e);
		return e;
	}

	private Conta fromEntity(Entity e) {
		Conta conta = new Conta();
		conta.setId(Long.valueOf(e.getKey().getId()).intValue());
		conta.setNome((String) e.getProperty("nome"));
		conta.setTipoConta(TipoConta.valueOf((String) e.getProperty("tipoConta")));
		return conta;
	}

}
